/*
 * matrickey.c
 *
 *  Created on: 2017年9月24日
 *      Author: WEY
 */

// TODO: 1. 检测多个按键按下的情况
// TODO: 2. 检测按键的状态，按下/保持/抬起

#include "matrickey.h"

#define KEY_MATRIC_ROW 4
#define KEY_MATRIC_COL 4
IOBit g_IoBit_Col[KEY_MATRIC_COL]={
	{
		0x56000050,
		0x56000054,
		2,
		2,
		1,
	},//key0,
	{
		0x56000050,
		0x56000054,
		6,
		2,
		3,
	},//key1
	{
		0x56000060,
		0x56000064,
		0,
		2,
		0,
	},//key2
	{
		0x56000060,
		0x56000064,
		10,
		2,
		5,
	},//key3
};
IOBit g_IoBit_Row[KEY_MATRIC_ROW]={
	{
		0x56000060,
		0x56000064,
		18,
		2,
		9,
	},//key4
	{
		0x56000040,
		0x56000044,
		22,
		2,
		11,
	},//key5
	{
		0x56000040,
		0x56000044,
		30,
		2,
		15,
	},//key7
	{
		0x56000010,
		0x56000014,
		2,
		2,
		1,
	},//key6
};

void SetKeyAttr(IOBit *BitPort,int attr){
	int conMask=(1<<BitPort->contbitWidth)-1;
	*((volatile unsigned *)BitPort->conAddr) &=~ (conMask<<BitPort->conBitShift);
	if(attr){
		*((volatile unsigned *)BitPort->conAddr) |= (0x1<<BitPort->conBitShift);//输出
		*((volatile unsigned *)BitPort->dataAddr)&= ~(0x1<<BitPort->dataBit);//低电平
	}
	else
		*((volatile unsigned *)BitPort->conAddr) |= (0x0<<BitPort->conBitShift);//输入
}
//
U32 IsKeyPressed(IOBit *bitPort,int num){
	//配置为输入端口
	U32 value;
	for(int i=0;i<num;i++){
		value=*((volatile unsigned *)bitPort[i].dataAddr);
		if(!(value & (1<<bitPort[i].dataBit)))
			return (i+1);
	}
	return 0;
}

void delayMs(int ms)
{
	int num1,num2;
	num1=400;
	num2=1000;
	while(ms-->0){
		while(num1-->0){
			while(num2-->0);
		}
	}
}

int scanKeyboard(void){
	static int lastPressKey=0;
	int pressedKey;
	int i;
	int pressedRowNo,pressedColNo;
	if(1){
		//设置行信号为输出方式
		for(i=0;i<sizeof(g_IoBit_Row)/sizeof(IOBit);i++){
			SetKeyAttr(&g_IoBit_Row[i],1);
		}
		//设置为输入模式
		for(i=0;i<sizeof(g_IoBit_Col)/sizeof(IOBit);i++){
			SetKeyAttr(&g_IoBit_Col[i],0);
		}
	}
	pressedColNo=IsKeyPressed(g_IoBit_Col,sizeof(g_IoBit_Col)/sizeof(IOBit));
	if(!pressedColNo){
		lastPressKey=0;
		return 0;
	}
	//延时20ms;
	//delayMs(20);
	for(i=0;i<sizeof(g_IoBit_Col)/sizeof(IOBit);i++){
			SetKeyAttr(&g_IoBit_Col[i],1);
	}
	//设置为输入模式
	for(i=0;i<sizeof(g_IoBit_Row)/sizeof(IOBit);i++){
			SetKeyAttr(&g_IoBit_Row[i],0);
	}
	pressedRowNo=IsKeyPressed(g_IoBit_Row,sizeof(g_IoBit_Row)/sizeof(IOBit));
	if(!pressedRowNo){
		lastPressKey=0;
		return 0;
	}
	pressedKey=(pressedRowNo-1)*KEY_MATRIC_COL+pressedColNo;
	if(pressedKey==lastPressKey)
		return 0;
	lastPressKey=pressedKey;
	return pressedKey;
}
